import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_bsbdj/utils/shared_preferences_util.dart';

class MusicPlay {
  String _playUrl;
  bool _isLocal = false;
  AudioPlayer _audioPlayer;
  static MusicPlay _musicPlay;
  bool isPlaying = false;
  AudioPlayerState _audioPlayerState = AudioPlayerState.STOPPED;

  static MusicPlay getInstance() {
    if (_musicPlay == null) {
      _musicPlay = MusicPlay();
    }
    return _musicPlay;
  }

  MusicPlay() {
    AudioPlayer.logEnabled = false;
    _audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
  }

  //时长监听
  MusicPlay setDurationChanged(Function funcation) {
    _audioPlayer.onDurationChanged.listen((duration) {
      funcation(duration);
    });
    return _musicPlay;
  }

  //播放进度监听
  MusicPlay setAudioPositionChanged(Function funcation) {
    _audioPlayer.onAudioPositionChanged.listen((duration) {
      funcation(duration);
    });
    return _musicPlay;
  }

  //播放状态变化监听
  MusicPlay setPlayerStateChanged(Function funcation) {
    _audioPlayer.onPlayerStateChanged.listen((duration) {
      _audioPlayerState = duration;
      funcation(duration);
    });
    return _musicPlay;
  }

  //播放完成监听
  MusicPlay setPlayerCompletion(Function funcation) {
    _audioPlayer.onPlayerCompletion.listen((drt) {
      funcation();
    });
    return _musicPlay;
  }

  //播放失败
  MusicPlay setPlayerError(Function funcation) {
    _audioPlayer.onPlayerError.listen((duration) {
      funcation(duration);
    });
    return _musicPlay;
  }

  void playMusic(String url, bool local) async {
    print(url);
    _isLocal = local;
    _playUrl = url;
    int result = await _audioPlayer.play(_playUrl, isLocal: _isLocal);
    //保存播放器的 playId
    SharedPrefrenceUtil.setStringValue("playId", _audioPlayer.playerId);
    if (result == 1) {
      print("开始播放");
      isPlaying = true;
    } else {
      print("打开资源失败");
      isPlaying = false;
    }
  }

  void seekTo(int position) {
    _audioPlayer.seek(Duration(milliseconds: position));
  }

  void replay() {
    playMusic(_playUrl, _isLocal);
  }

  void pause() {
    _audioPlayer.pause();
    isPlaying = false;
  }

  void stop() {
    _audioPlayer.release();
  }

  AudioPlayerState getPlayState() {
    return _audioPlayerState;
  }
}
